//-------------------------------------------------------------------
//	Copyright (c) 2012-2014 Zhirnov Andrey
//	This file is part of the "UXGEN-ES" project.
//	See copyright notice in "Engine.h".
//-------------------------------------------------------------------

#pragma once

#include "Base/Parallel/ParallelThread.h"

namespace Engine
{
namespace Base
{


	//
	// Timer Manager
	//

	class TimerManager : public BaseObject
	{
	// types
	public:
		typedef void (* OnElapsedFunc_t) (const BaseObjectPtr &, void *data);


	private:
		struct Timer
		{
			BaseObjectPtr	obj;
			OnElapsedFunc_t	func;
			void *			data;
			float			interval;
			///
			Timer () : func(null), data(null), interval(0.0f)
			{}

			Timer (const BaseObjectPtr &obj, OnElapsedFunc_t func, void *data, float interval) :
				obj(obj), func(func), data(data), interval(interval)
			{}

			void Call ()
			{
				func( obj, data );
			}
		};

		typedef array< Timer >	timer_array_t;


	// variables
	private:
		timer_array_t	_timers;


	// methods
	public:
		TimerManager (const EngineSubSystemsRef ess) : BaseObject(ess)
		{}

		~TimerManager ()
		{}


		void Update (float dt)
		{
			FOR( i, _timers )
			{
				if ( (_timers[i].interval -= dt) <= 0.0f )
				{
					_timers[i].Call();
					_timers.Erase( i );
					--i;
				}
			}
		}


		bool CreateTimer (float interval, const BaseObjectPtr &obj, OnElapsedFunc_t func, void *data = null)
		{
			CHECK_ERR( obj.IsNotNull() and func != null );

			_timers.PushBack( Timer( obj, func, data, interval ) );
			return true;
		}
	};





}	// Base
}	// Engine